import React, { Component } from 'react'
import {View,Text,Image,StatusBar,StyleSheet} from 'react-native'
import AsyncStorage from "@react-native-community/async-storage"
import {
    CodeField,
    Cursor,
    useBlurOnFulfill,
    useClearByFocusCell,
  } from 'react-native-confirmation-code-field';
import { Input } from 'react-native-elements';
import {pxToDp} from '../../../utils/stylesKits'
import vaildator from '../../../utils/vaildator'
import request from '../../../utils/request'
import Toast from '../../../utils/Toast'
import THButton from '../../../components/THButton'
import {ACCOUNT_LOGIN,ACCOUNT_VALIDATEVCODE} from '../../../utils/pathMap'
import {inject,observer} from 'mobx-react'

@inject('rootStore')
@observer

export default class Login extends Component {
    state = {
        //手机号码
        phoneNumber:'18665711978',
        //手机号码是否合法
        phoneVail:true,
        //是否显示登录页面
        showLogin:true,
        //验证码输入框的值
        vcodeTxt:'',
        //倒计时按钮的文本
        btnText:"重新获取",
        //是否在倒计时中
        isCounding:false
    }
    //登录框手机号码输入
    phoneNumberChangeText=(phoneNumber)=>{
        this.setState({ phoneNumber });
    }
    /**
     *1.对手机号码的合法性做校验 --正则
            1 不通过：提示
            2 将手机号码发送到后台对应接口 -> 获取验证码
                    1 发送一步请求的时候，自动显示等待框
                    2 请求回来 等待框自动隐藏
                    3 关键
                        1 等待框
                        2 自动？ -> axios的拦截器
            3 将登录页切换成验证码的界面
     *
     */
    phoneNumberSubmitEditing=async()=>{
        const {phoneNumber,showLogin,isCounding} = this.state
        const phoneVail = vaildator.validatePhone(phoneNumber)
        this.setState({ phoneVail });
        if(phoneVail){
            const res = await request.post(ACCOUNT_LOGIN,{phone:phoneNumber})
            console.log(res)
            if(res.code==='10000'){
                //请求成功
                this.setState({showLogin:!showLogin,isCounding:true})
                //开启定时器
                this.countDown()
            }
        }
    }

    //开启验证码的定时器
    countDown = ()=>{
        let seconds = 5
        this.setState({btnText:`重新获取(${seconds}s)`,isCounding:true})
        let timeId = setInterval(() => {
            seconds --
            this.setState({btnText:`重新获取(${seconds}s)`})
            if(!seconds){
                this.setState({btnText:`重新获取`,isCounding:false})
                clearInterval(timeId)
            }
        }, 1000);
    }
    
    //输入验证码完成事件
    VcodeOnSubmit=async ()=>{
        /**
         * 1 对验证码校验 长度
         * 2 将手机号码 和 验证码发送到后台 
         * 3 返回值有isNew
         * 4 新用户 -> 完善个人信息的页面
         * 5 老用户 -> 交友 - 首页
         * */
        const {vcodeTxt,phoneNumber} = this.state
        if(vcodeTxt.length!=6){
            Toast.message('验证码不正确',2000,'center');
            return
        }
        const res = await request.post(ACCOUNT_VALIDATEVCODE,{
            phone: phoneNumber,
            vcode: vcodeTxt
        })
        if(res.code==='10000'){
            //存储用户数据
            const {id:userId,isNew,token} = res.data 

            //存储在mobx
            this.props.rootStore.setUserInfo(phoneNumber,token,userId)

            //存储token到本地
            AsyncStorage.setItem('userInfo',JSON.stringify({
                mobile:phoneNumber,
                token,
                userId
            }))


            if(isNew){
                //跳转到新用户
                this.props.navigation.navigate('UserInfo')
            }else{
                //跳转到老用户
                this.props.navigation.navigate('Tabbar')
            }
        }else{
            console.log('验证码不正确')
        }

    }

    //验证码输入框事件改变
    onVcodeChange = (vcodeTxt)=>{
        this.setState({vcodeTxt})
    }

    //点击重新获取按钮
    repGerVcode = ()=>{
        this.countDown()
    }

    //渲染登录页面
    renderLogin = ()=>{
        const {phoneNumber,phoneVail} = this.state
        return (
            <View>
                {/* 内容 开始 */}
                <View>
                    {/* 标题 */}
                    <View style={{padding:pxToDp(20)}}>
                        <Text style={{fontSize:pxToDp(25),color:'#888',fontWeight:'600'}}>手机登录注册</Text>
                    </View>
                    {/* 输入框 */}
                    <Input
                    placeholder='请输入手机号码'
                    maxLength={11}
                    keyboardType='phone-pad'
                    value={phoneNumber}
                    inputStyle={{color:'#333'}}
                    onChangeText={this.phoneNumberChangeText}
                    errorMessage={phoneVail?'':'手机号码输入不正确'}
                    onSubmitEditing={this.phoneNumberSubmitEditing}
                    leftIcon={{ type: 'font-awesome', name: 'phone' ,color:'#ccc',size:pxToDp(20) }}
                    />
                </View>
                {/* 内容 结束 */}

                {/* 按钮 开始 */}
                    <View>
                        <View style={{width:"75%",height:pxToDp(40),alignSelf:'center'}}>
                            <THButton onPress={this.phoneNumberSubmitEditing} style={{borderRadius:pxToDp(20)}}>获取验证码</THButton>
                        </View>
                    </View>
                {/* 按钮 结束 */}
            </View>
        )
    }

    //渲染验证码页面
    renderVcode = ()=>{
        const {phoneNumber,btnText,isCounding} = this.state
        const styles = StyleSheet.create({
            root: {flex: 1, padding: 20},
            title: {textAlign: 'center', fontSize: 30},
            codeFieldRoot: {marginTop: 20},
            cell: {
              width: 40,
              height: 40,
              lineHeight: 38,
              fontSize: 24,
              borderBottomWidth: 2,
              borderColor: '#00000030',
              textAlign: 'center',
              color:'#7d53ea'
            },
            focusCell: {
              borderColor: '#7d53ea',
            },
          });
        return (
            <View style={{padding:pxToDp(20)}}>
                <View>
                    <Text style={{fontSize:pxToDp(25),color:'#888',fontWeight:'600'}}>输入6位验证码</Text>
                </View>
                <View style={{marginTop:pxToDp(10)}}>
                    <Text>已发到:+86{phoneNumber}</Text>
                </View>
                <View>
                    <CodeField
                        value={this.state.vcodeTxt}
                        onChangeText={this.onVcodeChange}
                        cellCount={6}
                        rootStyle={styles.codeFieldRoot}
                        onSubmitEditing={this.VcodeOnSubmit}
                        keyboardType="number-pad"
                        renderCell={({index, symbol, isFocused}) => (
                        <Text
                            key={index}
                            style={[styles.cell, isFocused && styles.focusCell]}>
                            {symbol || (isFocused ? <Cursor /> : null)}
                        </Text>
                        )}
                    />
                </View>
                <View style={{width:"75%",height:pxToDp(40),alignSelf:'center',marginTop:pxToDp(10)}}>
                    <THButton isCounding={isCounding} onPress={this.repGerVcode} style={{borderRadius:pxToDp(20)}}>
                        {btnText}
                    </THButton>
                </View>
            </View>
        )
    }

    render() {
        const {showLogin} = this.state
        return (
            <View>
                {/* 手机状态栏 开始 */}
                <StatusBar backgroundColor='transparent' translucent={true}/>
                {/* 手机状态栏 结束 */}
                
                {/* 背景图片 开始 */}
                {/* 200 单位 dp 单位px -> dp单位? */}
                <Image 
                    style={{
                    width:"100%",
                    height:pxToDp(220)}}
                    source={require('../../../soures/profileBackground.jpg')} />
                {/* 背景图片 结束 */}

                {
                    showLogin?this.renderLogin():this.renderVcode()
                }        
            </View>
        )
    }
}
